/********************************************************************************
* @File name: ultrasonic.h
* @Author: Loganx
* @Blog: https://www.cnblogs.com/loganxiang
* @Version: 1.0(2025-10-09)
* @Description: STC8A单片机超声波模块（IIC接口）测距
********************************************************************************
* 本软件使用了STC的STC8A官方库；
********************************************************************************/
#inclulde "ultrasonic.h"

uint32  Distance;

uint8 UltraData[3];
uint8 code UltraCmd = 0x01;

void UltrasonicInit(void){
    GPIO_InitTypeDef gpio;
    I2C_InitTypeDef i2c;

    gpio.Pin = ULTRASONIC_PIN;
    gpio.Mode = GPIO_PullUp;
    GPIO_Inilize(ULTRASONIC_GPIO,&gpio);

    #ifndef _I2C_INIT
    #define _I2C_INIT
    i2c.I2C_Mode = I2C_Mode_Master;
    i2c.I2C_Enable = ENABLE;
    I2C_Init(&i2c);

    NVIC_I2C_Init(I2C_Mode_Master,I2C_ESTAI|I2C_ERXI|I2C_ETXI|I2C_ESTOI,Priority_0);
    I2C_SW(ULTRASONIC_SW);
    #endif
}

//系统定时器回调函数，系统定时器中调用
//定时器周期应大于100ms，保证调用间隔模块测距完成
void SystickCallbackUltrasonic(void){
    
    I2C_ReadNbyte(ULTRASONIC_DEV_ADDR,ULTRASONIC_DATA_ADDR,pUltroData,3);
    Distance = (uint32)*UltroData;
    //这里可根据温度进行补偿校正
    I2C_WriteNbyte(ULTRASONIC_DEV_ADDR,ULTRASONIC_CMD_ADDR,UltraCmd,1);
}

uint32 GetDistance(void){
    return Distance;
}